package com.leetcode.partition1;

/**
 * @author `RKC`
 * @date 2021/8/8 10:17
 */
public class LC63不同路径2 {

    public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid[0][0] == 1 || obstacleGrid[obstacleGrid.length - 1][obstacleGrid[0].length - 1] == 1) return 0;
        return dynamicProgramming(obstacleGrid);
    }

    public static void main(String[] args) {
        int[][] obstacleGrid = {
                {0, 0, 0},
                {0, 1, 0},
                {0, 0, 0}
        };
//        int[][] obstacleGrid = {
//                {0, 0},
//                {1, 1},
//                {0, 0}
//        };
        System.out.println(uniquePathsWithObstacles(obstacleGrid));
    }

    private static int memoization(int[][] obstacleGrid, int i, int j, int[][] memo) {
        if (i >= obstacleGrid.length || j >= obstacleGrid[0].length || obstacleGrid[i][j] == 1) return 0;
        if (i == obstacleGrid.length - 1 && j == obstacleGrid[0].length - 1) return 1;
        memo[i][j] = memoization(obstacleGrid, i + 1, j, memo) + memoization(obstacleGrid, i, j + 1, memo);
        return memo[i][j];
    }

    //深度搜索：Time Limit Exceeded
    private static int dfs(int[][] obstacleGrid) {
        return dfs(0, 0, obstacleGrid);
    }

    private static int dfs(int i, int j, int[][] obstacleGrid) {
        if (i == obstacleGrid.length - 1 && j == obstacleGrid[0].length - 1) return 1;
        if (i >= obstacleGrid.length || j >= obstacleGrid[0].length || obstacleGrid[i][j] == 1) return 0;
        return dfs(i + 1, j, obstacleGrid) + dfs(i, j + 1, obstacleGrid);
    }

    //动态规划
    private static int dynamicProgramming(int[][] obstacleGrid) {
        int[][] dp = new int[obstacleGrid.length][obstacleGrid[0].length];
        //初始化，当一直向右或者一直向下遇到障碍就应该停止初始化
        for (int i = 0; i < obstacleGrid.length && obstacleGrid[i][0] == 0; i++) dp[i][0] = 1;
        for (int j = 0; j < obstacleGrid[0].length && obstacleGrid[0][j] == 0; j++) dp[0][j] = 1;

        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[i].length; j++) {
                //如果是障碍则直接跳过
                if (obstacleGrid[i][j] == 1) continue;
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        return dp[dp.length - 1][dp[0].length - 1];
    }
}
